import { NzCheckBoxOptionInterface } from 'ng-zorro-antd/checkbox';

/// 不能是OnPush模式。因为OnPush模式下，如果model的内部数据变化，不会触发变更检测。
export class SelectAllModel {
  private _isAllSelected = false;
  public get isAllSelected() {
    return this._isAllSelected;
  }

  private _indeterminate = false;
  public get indeterminate() {
    return this._indeterminate;
  }

  constructor(public options: NzCheckBoxOptionInterface[]) {
    this.update();
  }

  public static From(
    options: string[],
    selected: string[] = []
  ): SelectAllModel {
    const optionInterfaces = options.map(
      (item) =>
        ({
          label: item,
          value: item,
        } as NzCheckBoxOptionInterface)
    );
    optionInterfaces.forEach((item) => {
      item.checked = selected.indexOf(item.value) !== -1;
    });
    return new SelectAllModel(optionInterfaces);
  }

  selectAll(checked: boolean) {
    this.options.forEach((item) => (item.checked = checked));
    this.update();
  }

  selectItem(value: string, checked: boolean) {
    this.options.forEach((item) => {
      if (item.value === value) {
        item.checked = checked;
      }
    });
    this.update();
  }

  private update() {
    this._isAllSelected = this.options.every((item) => item.checked);
    this._indeterminate =
      this.options.some((item) => item.checked) && !this._isAllSelected;
  }
}
